/***************************************************************************
 *   Copyright (C) 2009 by umbacos@gmail.com                               *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "udm-common.h"

char* dcgi;
char* droo;
char* dbin;
char* wget;
char* ctor;
char* dwww;
char* dufb;
char* ddnl;
char* dtrk;
char* fcnf;
char* argv0;
char* filter;
char* pidfile;

void get_post_cookie();
void get_directories(char * file);
void * xmalloc(size_t size);
char * getPID(char* file);
char * pipe_cmd(const char * cmd);
int filter_select(struct dirent *entry);
void print_headers(int final);
void send_message(char * msg, char * inf);
char * escape_hyphens(char * str, char * ch);
void strip_last(char * str, char ch);

static const char cb64[] =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char * decode64(char * input) {
	unsigned char chr1, chr2, chr3;
	unsigned char enc1, enc2, enc3, enc4;

	char * output = xmalloc(strlen(input));
	int i = 0;

	do {
		enc1 = strchr(cb64, input[i++]) - cb64;
		enc2 = strchr(cb64, input[i++]) - cb64;
		enc3 = strchr(cb64, input[i++]) - cb64;
		enc4 = strchr(cb64, input[i++]) - cb64;

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		output[i / 4 * 3 - 3] = (char) chr1;

		if (enc3 != 64) {
			output[i / 4 * 3 - 2] = (char) chr2;
		}
		if (enc4 != 64) {
			output[i / 4 * 3 - 1] = (char) chr3;
		}

		chr1 = chr2 = chr3 = '\0';
		enc1 = enc2 = enc3 = enc4 = '\0';

	} while (i < strlen(input));

	return output;
}

void do_get_session(char * user, char * pass) {

	char cmdp[1000];
	char * cleanpass;
	char * pipd;
	char * token;

	memset(&cmdp, 0, 1000);

	sprintf(
			cmdp,
			"%s -SO- http://127.0.0.1:9091/transmission/rpc?method=session-get",
			wget);

	pipd = pipe_cmd(cmdp);

	cleanpass = NULL;
	token = strtok(pipd, "\n");
	while (token) {
		while (token[0] == ' ')
			token++;
		if (strstr(token, "X-Transmission-Session-Id:") == token) {
			cleanpass = strdup(token);
#ifdef DEBUG
			mylog("session-header: ", cleanpass);
#endif
		}
		token = strtok(NULL, "\n");
	}

	if (cleanpass != NULL)
		send_message("OK ", cleanpass);
	else
		send_message("Authorization failed", "");
}

void do_proxy(char * file, char * para) {
	char cmdp[1000];

	memset(&cmdp, 0, 1000);

	sprintf(cmdp, "%s %s http://127.0.0.1:9091/transmission/rpc?%s", wget, para, file);

#ifdef DEBUG
	mylog("popen:", cmdp);
#endif

	send_message(pipe_cmd(cmdp), "");
}

void do_get_settings() {
	pipe_cmd("killall transmission-daemon");
	pipe_cmd("transmission-daemon -T -a 127.0.0.1");
	sleep(1);
	pipe_cmd("killall transmission-daemon");
	sleep(1);
	pipe_cmd("transmission-daemon -T -a 127.0.0.1");
	send_message(pipe_cmd("transmission-daemon -d"), "");
}

int main(int argc, char** argv) {

	char cmd[11];
	char fil[501];
	char par[501];

	memset(&cmd, 0, 10);
	memset(&fil, 0, 500);
	memset(&par, 0, 500);

	get_directories(strdup(argv[0]));
	get_post_cookie();

	if (getenv("FORM_cmd"))
		strncpy(cmd, getenv("FORM_cmd"), 10);
	else
		send_message("zcmd: no command provided", NULL);

	if (getenv("FORM_file"))
		strncpy(fil, getenv("FORM_file"), 500);

	if (getenv("FORM_para"))
		strncpy(par, getenv("FORM_para"), 500);
#ifdef DEBUG
	mylog("fil:", fil);
	mylog("cmd:", cmd);
	mylog("par:", par);
#endif

	/* Interpret */
	if (strstr(cmd, CMD_TRANS_GET_SESSION) != 0)
		do_get_session(fil, par);
	else if (strstr(cmd, CMD_TRANS_PROXY) != 0)
		do_proxy(fil, par);
	else if (strstr(cmd, CMD_TRANS_RSETTINGS) != 0)
		do_get_settings();
	else
		send_message("Unknown command:", cmd);

	send_message("OK", "");

	return 0;
}
